package com.kawa.service.impl;


import com.kawa.entity.po.User;
import com.kawa.entity.vo.LoginResult;
import com.kawa.mapper.UserLoginMapper;
import com.kawa.service.LoginService;
import com.kawa.util.MD5Util;
import com.kawa.util.RedisUtil;
import com.kawa.util.TokenPrefixUtil;
import com.kawa.util.TokenUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.kawa.entity.po.table.UserTableDef.USER;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private MD5Util md5Util;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public LoginResult UserLogin(String username, String password, String CaptchaId,String captchaCode
    ) {


        // 构建查询条件（支持手机号/邮箱/用户名登录）
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select().from("user")
                .where(USER.USERNAME.eq(username)
                        .or(USER.MOBILE.eq(username))
                        .or(USER.EMAIL.eq(username))
                        .and(USER.PASSWORD.eq(password)));


        // 查询用户
        User user = userLoginMapper.selectOneByQuery(queryWrapper);
        if (user == null) {
            return null; // 登录失败
        }


        LoginResult result = new LoginResult();
        //验证码验证
        String storedCaptcha = redisUtil.get(CaptchaId);
        if (storedCaptcha != null) {
            if (storedCaptcha.equalsIgnoreCase(captchaCode)) {
                // 生成Token（使用用户ID作为subject更安全）
                String userId = user.getId().toString();
                String flashToken =  tokenUtil.generateSimpleJwtToken(userId);
                String foverToken = tokenUtil.generateJwtToken(userId, null, 3600 * 1000 * 24);

                // 存储Token关系（长期Token:短期Token）

                String prefixedFoverToken = TokenPrefixUtil.storeWithPrefix(
                        redisUtil,
                        foverToken,
                        flashToken,
                        24,
                        TimeUnit.HOURS,
                        user
                );

                //删除验证码并储存信息
                redisUtil.delete(CaptchaId);
                result.setUsername(user.getUsername());
                result.setAccess_token(prefixedFoverToken);     // 长期Token
                result.setRefresh_token(flashToken);    // 短期Token
                result.setExpire(86400L);
                return result;
            } else {
                return null;
            }
        } else {
            return null;
        }


    }
}
